<template>
  <n-card :bordered="false" class="proCard">
    <BasicTable
      title="管理员列表"
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
    >
      <template #toolbar>
        <n-drawer v-model:show="active" :width="502">
          <n-drawer-content>
            <template #header>
              新增管理员
            </template>
            <template #default>
              <n-form
                :label-width="80"
                :model="formValue"
              >
                <n-form-item label="管理员名称">
                  <n-input v-model:value="formValue.name"/>
                </n-form-item>
              </n-form>
            </template>
            <template #footer>
              <n-button type="primary" @click="save(formValue.name)">保存</n-button>
            </template>
          </n-drawer-content>
        </n-drawer>
        <n-drawer v-model:show="activeInfo" :width="502">
          <n-drawer-content>
            <template #header>
              编辑角色
            </template>
            <template #default>
              <n-form
                :label-width="80"
                :model="formValue"
              >
                <n-form-item label="管理员名称">
                  <n-input v-model:value="formValue.name"/>
                </n-form-item>
                <n-form-item label="角色列表">
                  <n-checkbox-group v-model:value="formValue.roles">
                    <n-space item-style="display: flex;">
                      <n-checkbox v-for="item in roles" :value="item.id" :label="item.name"/>
                    </n-space>
                  </n-checkbox-group>
                </n-form-item>
                <n-form-item label="是否启用">
                  <n-radio-group v-model:value="formValue.status" name="radiogroup">
                    <n-space>
                      <n-radio v-for="song in songs" :key="song.value" :value="song.value">
                        {{ song.label }}
                      </n-radio>
                    </n-space>
                  </n-radio-group>
                </n-form-item>
              </n-form>
            </template>
            <template #footer>
              <n-button type="primary" @click="update(formValue.id, formValue.name, formValue.status, formValue.roles)">保存</n-button>
            </template>
          </n-drawer-content>
        </n-drawer>
        <n-button type="primary" @click="activate">新增</n-button>
      </template>
    </BasicTable>
  </n-card>
</template>
<script lang="ts">
import {defineComponent, h, reactive, ref, toRefs} from 'vue';
import {BasicTable, TableAction} from '@/components/Table';
import {columns} from './basicColumns';
import {FormInst, useDialog, useMessage} from 'naive-ui';
import {DeleteOutlined, EditOutlined} from "@vicons/antd";
import {adminPage, deleteAdmin, saveAdmin, updateAdmin} from "@/api/admin";
import {adminRoleIds, rolePage} from "@/api/role";

export default defineComponent({
  components: { BasicTable },
  setup() {
    const formValue = ref({
      id: '',
      name: '',
      status: '',
      roles: [],
    })
    function handleEdit(record) {
      getRoles(record);
      activateInfo();
      formValue.value.id = record.id;
      formValue.value.name = record.username;
      formValue.value.status = record.status;
    }

    // 增
    function save(name) {
      saveAdmin(name).then(() => {
        active.value = false;
        reloadTable();
        message.success("新增成功");
      }).catch(e => message.error(e.message));
    }

    // 删
    function handleDelete(record) {
      dialog.warning({
        title: '警告',
        content: '确认删除？',
        positiveText: '确认',
        negativeText: '取消',
        onPositiveClick: () => {
          deleteAdmin(record.id).then(() => {
            activeInfo.value = false;
            reloadTable();
            message.success("删除成功");
          }).catch(e => message.error(e.message));
        },
      })
    }

    // 改
    function update(id, name, status, roles) {
      updateAdmin(id, name, status, roles).then(() => {
        activeInfo.value = false;
        reloadTable();
        message.success("修改成功");
      }).catch(e => message.error(e.message));
    }

    // 查
    const loadDataTable = async (params) => {
      return await adminPage(params).catch(e => message.error(e.message));;
    };

    // 管理员角色
    const roles = ref([]);
    const getRoles = async (record) => {
      await rolePage({}).then(res => {
        roles.value = res.list;
      }).catch(e => message.error(e.message));
      await adminRoleIds(record.id).then(res => {
        formValue.value.roles = res;
      }).catch(e => message.error(e.message));
    }

    const active = ref(false)
    const activate = () => {
      active.value = true
    }
    const activeInfo = ref(false)
    const activateInfo = () => {
      activeInfo.value = true
    }
    const actionRef = ref();
    const state = reactive({
      params: {},
      actionColumn: {
        width: 150,
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        align: 'center',
        render(record) {
          return h(TableAction, {
            style: 'text',
            actions: createActions(record),
          });
        },
      },
    });

    const formRef = ref<FormInst | null>(null)
    const message = useMessage();
    const dialog = useDialog();

    function createActions(record) {
      if(record.isAdmin == 1) {
        return [];
      }
      return [
        {
          label: '编辑',
          type: 'primary',
          icon: EditOutlined,
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
        },
        {
          label: '删除',
          type: 'error',
          icon: DeleteOutlined,
          onClick: handleDelete.bind(null, record),
          ifShow: () => {
            return true;
          },
        },
      ];
    }

    function onCheckedRow(rowKeys) {
      console.log(rowKeys);
    }

    function reloadTable() {
      actionRef.value.reload();
    }

    return {
      ...toRefs(state),
      columns,
      actionRef,
      loadDataTable,
      onCheckedRow,
      reloadTable,
      active,
      activate,
      activeInfo,
      activateInfo,
      save,
      roles,
      getRoles,
      update,
      formRef,
      formValue,
      songs: [
        {
          value: 1,
          label: "是"
        },
        {
          value: 0,
          label: '否'
        },
      ]
    };
  },
});
</script>
